{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "dedicated-alexander",
   "metadata": {},
   "source": [
    "# 在 Paddle Quantum 中模拟含噪量子电路\n",
    "\n",
    "<em> Copyright (c) 2021 Institute for Quantum Computing, Baidu Inc. All Rights Reserved. </em>"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "weird-functionality",
   "metadata": {},
   "source": [
    "## 噪声简介\n",
    "\n",
    "在理想模型中，我们通常假设量子电路是在一个**封闭系统**中执行的。然而在真实的量子设备中，系统会通过和环境的相互作用产生**非相干噪声（incoherent noise）**。在近期的量子设备上，噪声的影响是难以忽略的。因此，如何设计在噪声影响下依然鲁棒（robust）的量子算法对于量子计算的实用化来说是至关重要的。利用 Paddle Quantum 中的噪声模块，我们现在可以在设计并模拟量子算法的同时研究噪声对其的影响，从而进一步的探索对应的错误缓释（error mitigation）方案。\n",
    "\n",
    "## Paddle Quantum 中的噪声建模\n",
    "\n",
    "### 噪声模型与量子信道\n",
    "\n",
    "对于一个封闭的量子系统，其演化总是幺正（unitary）的。数学上，我们通常用酉变换的语言来描述一个参数化量子电路 $U(\\vec{\\theta})$ 的作用， \n",
    "\n",
    "$$\n",
    "\\rho \\longrightarrow U(\\vec{\\theta}) \\rho U^\\dagger(\\vec{\\theta}),\n",
    "\\tag{1}\n",
    "$$\n",
    "\n",
    "其中 $\\rho$ 表示初始量子态， $\\vec{\\theta}$ 表示电路的参数向量。那么最简单的一类噪声模型，是我们在控制量子系统执行具体逻辑门的时候参数的噪声化，\n",
    "\n",
    "$$\n",
    "\\rho \\longrightarrow U(\\vec{\\theta}+\\vec{\\epsilon}) \\rho U^\\dagger(\\vec{\\theta}+\\vec{\\epsilon}),\n",
    "\\tag{2}\n",
    "$$\n",
    "\n",
    "其中 $\\vec{\\epsilon}$ 可以是从高斯分布中采样出的白噪声。这样的噪声被称为**相干噪声（coherent noise）**，通常是由于硬件系统没有校准或者量子控制层面的误差。在某些特定情况下，相干噪声会比非相干噪声更具有破坏性 [1]。此外，值得注意的是相干噪声的建模也是用酉变换的语言 $U(\\vec{\\epsilon})$ 来描述的。\n",
    "\n",
    "相比于相干噪声，人们更为关注的问题是**开放系统**中的产生的非相干噪声，这样一个系统的演化往往是非幺正（non-unitary）的。这种情况下，我们需要通过一个更广义的映射来描述系统的演化，即 $\\rho \\longrightarrow \\mathcal{E}(\\rho)$，这种映射也被称之为一个**量子信道（quantum channel）**。为了方便讨论，我们这里采用 *operator-sum representation* [2] 将一个量子信道表示为\n",
    "\n",
    "$$\n",
    "\\mathcal{E}(\\rho) =  \\sum_{k=0}^{m-1} E_k \\rho E_k^{\\dagger},\n",
    "\\tag{3}\n",
    "$$\n",
    "\n",
    "其中 $\\{E_k\\}$ 被称为 *Kraus* 算符，同时还满足完备性条件 $\\sum_k E_k^\\dagger E_k = I$。注意到，量子信道数学上是 completely positive 和 trace-preserving 的。\n",
    "\n",
    "\n",
    "利用这种表示方法，我们可以直观的理解非相干噪声是如何影响量子态的：对于一个一开始处于纯态 $\\rho = |\\psi\\rangle\\langle \\psi|$ 的量子系统，经过一个噪声量子信道（例如 $m = 2$ ）时，我们将得到一个混态 $\\mathcal{E}(\\rho) = E_0 \\rho E_0^\\dagger + E_1 \\rho E_1^\\dagger$。以简单的单个量子比特上的比特反转（bit flip）噪声为例，其表达形式为\n",
    "\n",
    "$$\n",
    "\\mathcal{E}_{BF}(\\rho) = (1 - p) I \\rho I+ p X \\rho X,\n",
    "\\tag{4}\n",
    "$$\n",
    "\n",
    "其中 $X,I$ 是泡利矩阵。 对应的 *Kraus* 算符为：\n",
    "\n",
    "$$\n",
    "E_0 = \\sqrt{1-p}\n",
    "\\begin{bmatrix}\n",
    "1 &0 \\\\\n",
    "0& 1 \n",
    "\\end{bmatrix},\n",
    "E_1 = \\sqrt{p}\n",
    "\\begin{bmatrix}\n",
    "0& 1 \\\\\n",
    "1&0\n",
    "\\end{bmatrix}.\n",
    "\\tag{5}\n",
    "$$\n",
    "\n",
    "该信道的物理含义可以理解为存在 $p$ 的概率将 $|0\\rangle$ 态反转到 $|1\\rangle$ 态上，反之亦然。在 Paddle Quantum 中，可以通过 `Circuit.bit_flip(p, which_qubit)` 来添加该信道，其中 `p` 代表噪声大小。\n",
    "\n",
    "**注释：** 对于一个量子信道，其 *Kraus* 算符表示未必是唯一的 [3]。"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "transsexual-hayes",
   "metadata": {},
   "source": [
    "### Paddle Quantum 中添加信道的方式\n",
    "\n",
    "接下来我们以比特反转信道为例，展示如何用 Paddle Quantum 中的噪声模块来实现对噪声的模拟。首先，将一个量子比特初始化为 $|0\\rangle$ 态。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "scheduled-attraction",
   "metadata": {
    "ExecuteTime": {
     "end_time": "2021-04-08T05:16:08.247239Z",
     "start_time": "2021-04-08T05:16:08.036136Z"
    }
   },
   "outputs": [
    {
     "data": {
      "image/png": "iVBORw0KGgoAAAANSUhEUgAAAYIAAAEDCAYAAAA4FgP0AAAAOXRFWHRTb2Z0d2FyZQBNYXRwbG90bGliIHZlcnNpb24zLjUuMSwgaHR0cHM6Ly9tYXRwbG90bGliLm9yZy/YYfK9AAAACXBIWXMAAAsTAAALEwEAmpwYAAARqUlEQVR4nO3de7BdZX3G8e+TcBEFpULqYC6CNWiDCmJER20Fr8SqwWtBqpWqkQoWp1OVdqzUaqdaL60WNKZK8TIFa0VEjTBWReqtQigXg0YjF0mhI6j1WsXIr3/sHdnu7HP2Tsjah+T9fmbOnL3e913r/JJJ8mS9611rpaqQJLVr3lwXIEmaWwaBJDXOIJCkxhkEktQ4g0CSGmcQSFLjdpvrArbV/vvvXwceeOBclyFJO5V169bdUlULRvXtdEFw4IEHcumll851GZK0U0ly/Ux9Tg1JUuMMAklqnEEgSY0zCCSpcQaBJDWusyBIcmaS7yT56gz9SfL2JBuTXJnk8K5qkSTNrMszgrOAo2fpXwEs7X+tAt7ZYS2SpBl0FgRVdTHwvVmGrATeVz1fBvZNckBX9UiSRpvLG8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DPcGOSvZMcOdB0GLc/42l4n32Am/oXmI8fdez+dNa1SZ7dP36SHDrbL1zaFgaBdlnVWwnxdOBZ/WcsfRe4rar+pj/kC/T+p34VvQu/lw3s/hPgkCTr6F3Q/esRP2IN8Mkknx1qD/DKJBuSXA68ltvPBs4BXtFfWvpbwF8C/wl8it4FZmYYdzzwwiRX0DvTWblNvxnSLFw1pGb0V+2cDTyjqtaNGy+1wiCQpMY5NSRJjTMIJKlxBoEkNc4gkKTGGQSS1DiDQJIaZxBIUuP+H8qMdZflk6M0AAAAAElFTkSuQmCC",
      "text/plain": [
       "<Figure size 432x288 with 1 Axes>"
      ]
     },
     "metadata": {
      "needs_background": "light"
     },
     "output_type": "display_data"
    },
    {
     "data": {
      "text/plain": [
       "{'0': 1.0, '1': 0.0}"
      ]
     },
     "execution_count": 5,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "import paddle_quantum\n",
    "from paddle_quantum.ansatz import Circuit\n",
    "from paddle_quantum import Backend\n",
    "\n",
    "# 切换至密度矩阵模式\n",
    "paddle_quantum.set_backend('density_matrix')\n",
    "\n",
    "# 设置量子比特数\n",
    "num_qubits = 1\n",
    "\n",
    "# 初始化量子电路\n",
    "cir = Circuit(num_qubits)\n",
    "\n",
    "# 制备 |0> 态\n",
    "init_state = paddle_quantum.state.zero_state(num_qubits)\n",
    "\n",
    "# 进行计算基上测量\n",
    "cir(init_state).measure(shots = 1024, plot = True)\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "indian-slave",
   "metadata": {},
   "source": [
    "之后，我们加上一个 $p=0.1$ 的比特反转噪声，并测量通过信道之后的量子比特。 \n",
    "**注释：** 噪声信道只支持在 density matrix 模式下运行。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "fiscal-literature",
   "metadata": {
    "ExecuteTime": {
     "end_time": "2021-04-08T05:16:09.221527Z",
     "start_time": "2021-04-08T05:16:08.977847Z"
    },
    "scrolled": true
   },
   "outputs": [
    {
     "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ueHlVfWuH/EOpeZ4RaFf2SGDNYENV/Ri4jt79E9tyX+CyqjoM+Arw5qHjvI/es5qOHAyBft8P6L373vVJzktyUpLdquqSfvtrq+rQqvoucH5VPb5/5nA18LKtjFsOvKqqHgf8BXD2dv9rSFvhfQTalYXew/VGtY9zO/Dx/uuP0ZtimlhVnZLk0cAz6P3iPgp46Yihj0rydmAfYC967+j3m8UmewFPAj7Rm+0CYOx1DmlSBoF2Zeu4c1oF+PXU0P70pnQexW+eFd9rG8fa7jnUqloLrE3yUeBaRgfBucBxVXVFkpcCR4wYsxvwv1V16PbWIE3CqSHtyr4I3CfJSwCSzALOAM7sz91fBxyaZLck8+nddX2H3ehdQwB4EfC1Ece/Fdh7uDHJXkmOGGg6lDuf8TS8z97Azf0LzCeNOnZ/OuvaJH/QP36SHLKtb1zaHgaBdlnVWwnxPOD4/jOWvg/cXlV/0x/ydXp/qa+ld+H3soHdfwo8Mskaehd03zriSywHPp/ky0PtAV6XZH2Sy4G3cOfZwArgtf2lpb8NvBH4D+AL9C4ws5VxJwEvS3IFvTOdxdv1jyFtg6uG1Iz+qp3zgOdX1Zpx46VWGASS1DinhiSpcQaBJDXOIJCkxhkEktQ4g0CSGmcQSFLjDAJJatz/A823Ny8L3A8mAAAAAElFTkSuQmCC",
      "text/plain": [
       "<Figure size 432x288 with 1 Axes>"
      ]
     },
     "metadata": {
      "needs_background": "light"
     },
     "output_type": "display_data"
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "经过了 bit flip 信道之后的量子态是：\n",
      " [[0.8999999+0.j 0.       +0.j]\n",
      " [0.       +0.j 0.1      +0.j]]\n"
     ]
    }
   ],
   "source": [
    "# 噪声水平\n",
    "p = 0.1\n",
    "\n",
    "# 添加比特反转信道\n",
    "cir.bit_flip(p, 0)\n",
    "\n",
    "# 执行电路\n",
    "# 注释：噪声信道只能在 density matrix 模式下运行\n",
    "fin_state = cir(init_state)\n",
    "\n",
    "# 测量结果\n",
    "fin_state.measure(shots = 1024, plot = True)\n",
    "print('经过了 bit flip 信道之后的量子态是：\\n', fin_state.data.numpy())"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "bibliographic-undergraduate",
   "metadata": {},
   "source": [
    "可以看到，经过了比特反转信道（概率为 $p=0.1$）之后的量子态变成了混合态 $0.9 | 0 \\rangle \\langle 0 | + 0.1 | 1 \\rangle \\langle 1 |$。\n",
    "\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "million-diagnosis",
   "metadata": {},
   "source": [
    "### 常用噪声信道\n",
    "\n",
    "除了比特反转信道之外，Paddle Quantum 也支持模拟其他常用的噪声信道。\n",
    "\n",
    "\n",
    "- **相位反转信道（Phase Flip Channel）**\n",
    "\n",
    "  与比特反转信道类似，相位反转信道会以 $p$ 的概率来反转一个量子比特的相位，其表达形式为\n",
    "  \n",
    "  $$\n",
    "  \\mathcal{E}_{PF}(\\rho) =  (1 - p) \\rho + p Z \\rho Z.\n",
    "  \\tag{6}\n",
    "  $$\n",
    "\n",
    "\n",
    "- **比特相位反转信道（Bit-Phase Flip Channel）**\n",
    "\n",
    "  $$\n",
    "  \\mathcal{E}_{BPF}(\\rho) = (1-p) \\rho + p Y \\rho Y.\n",
    "  \\tag{7}\n",
    "  $$\n",
    "\n",
    "\n",
    "- **去极化信道 （Depolarizing Channel）**\n",
    "\n",
    "  通过去极化信道之后，将会有 $p$ 的概率处于最大混态 $I/2$ 和 $1-p$ 的概率维持不变。可以表示为对称地施加泡利噪声，\n",
    "  \n",
    "  $$\n",
    "  \\mathcal{E}_{D}(\\rho) = (1 - p) \\rho + \\frac{p}{3}\n",
    "  \\left( X \\rho X+ Y \\rho Y + Z \\rho Z \\right).\n",
    "  \\tag{8}\n",
    "  $$\n",
    "\n",
    "\n",
    "- **泡利信道（Pauli Channel）**\n",
    "\n",
    "    该信道会以非对称的形式施加泡利噪声。表达形式为\n",
    "  \n",
    "  $$\n",
    "  \\mathcal{E}_{Pauli}(\\rho) = (1 - p_x - p_y - p_z) \\rho + p_x X \\rho X + p_y Y \\rho Y + p_z Z \\rho Z.\n",
    "  \\tag{9}\n",
    "  $$\n",
    "\n",
    "\n",
    "- **振幅阻尼信道（Amplitude Damping Channel）**\n",
    "\n",
    "  振幅阻尼信道可以用来模拟当系统受到**能量耗散**时引入的噪声。表达形式为，\n",
    "  \n",
    "  $$\n",
    "  \\mathcal{E}_{AD}(\\rho) = E_0 \\rho E_0^\\dagger + E_1 \\rho E_1^\\dagger,\n",
    "  \\tag{10}\n",
    "  $$\n",
    "  \n",
    "  其中 $\\gamma$ 表示耗散系数，\n",
    "  \n",
    "  $$\n",
    "  E_0 = \n",
    "  \\begin{bmatrix}\n",
    "   1 & 0 \\\\ 0 & \\sqrt{1 - \\gamma}\n",
    "  \\end{bmatrix},\n",
    "  E_1 = \n",
    "  \\begin{bmatrix}\n",
    "   0 & \\sqrt{\\gamma} \\\\ 0 & 0\n",
    "  \\end{bmatrix}.\n",
    "  \\tag{11}\n",
    "  $$ \n",
    "\n",
    "\n",
    "- **相位阻尼信道（Phase Damping Channel）**\n",
    "\n",
    "  相位阻尼信道描述的是当系统没有与外界环境交换能量，却损失了**量子信息**的情况下的噪声模型。其表达形式为\n",
    "  \n",
    "  $$\n",
    "  \\mathcal{E}_{PD}(\\rho) = E_0 \\rho E_0^\\dagger + E_1 \\rho E_1^\\dagger,\n",
    "  \\tag{12}\n",
    "  $$\n",
    "  \n",
    "  其中 $\\gamma$ 表示损失系数，\n",
    "  \n",
    "  $$\n",
    "  E_0 = \n",
    "  \\begin{bmatrix}\n",
    "   1 & 0 \\\\ 0 & \\sqrt{1 - \\gamma}\n",
    "  \\end{bmatrix}, \n",
    "  E_1 = \n",
    "  \\begin{bmatrix}\n",
    "   0 & 0 \\\\ 0 & \\sqrt{\\gamma}\n",
    "  \\end{bmatrix}.\n",
    "  \\tag{13}\n",
    "  $$\n",
    "\n",
    "\n",
    "- **广义振幅阻尼信道（Generalized Amplitude Damping Channel）**\n",
    "\n",
    "  该信道描述的是系统与外界环境在**有限温度下交换能量**的噪声模型，同时也是**超导量子计算中的常见噪声** [4]。其表达形式较为复杂，感兴趣的读者可以进一步的阅读 [API 文档](https://qml.baidu.com/api/paddle_quantum.circuit.uansatz.html) 和相应的参考文献。\n",
    "\n",
    "\n",
    "**注释：** 在 Paddle Quantum 中，我们可以通过 `Circuit.phase_flip()`，`Circuit.bit_phase_flip()`， `Circuit.depolarizing()`，`Circuit.pauli_channel()`, `Circuit.amplitude_damping()`，`Circuit.phase_damping()`以及 `Circuit.generalized_amplitude_damping()` 来添加上述噪声。\n",
    "\n",
    "**注释：** 通常会选择振幅阻尼信道和相位阻尼信道来建模实际量子设备中的噪声，因为这两种信道可以较好的描述真实量子系统中的物理过程（可以用来建模 $T_1$ 和 $T_2$ 噪声）。"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "alert-senator",
   "metadata": {},
   "source": [
    "### 自定义信道\n",
    "\n",
    "此外，我们也可以通过 `Circuit.kraus_repr()` 来向电路中添加自定义噪声。具体的，该方法支持用自定义的 *Kraus* 算符来建模任意的噪声模型，我们自定义的方式来搭建比特反转信道为例："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "mobile-death",
   "metadata": {
    "ExecuteTime": {
     "end_time": "2021-04-08T05:17:30.681411Z",
     "start_time": "2021-04-08T05:17:30.658883Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "经过了自定义信道之后的量子态是：\n",
      " [[0.90000004+0.j 0.        +0.j]\n",
      " [0.        +0.j 0.1       +0.j]]\n",
      "\n",
      "经过了比特反转信道之后的量子态是：\n",
      " [[0.8999999+0.j 0.       +0.j]\n",
      " [0.       +0.j 0.1      +0.j]]\n",
      "\n",
      "两个态是否相同？ True\n"
     ]
    }
   ],
   "source": [
    "import paddle\n",
    "import numpy as np\n",
    "\n",
    "# 设置噪声参数\n",
    "p = 0.1\n",
    "\n",
    "# 我们用自定义的 Kraus 算符来描述一个比特反转信道\n",
    "complex_dtype = paddle_quantum.get_dtype()\n",
    "e_0 = paddle.to_tensor(np.sqrt(1 - p) * np.array([[1, 0], [0, 1]], dtype=complex_dtype))\n",
    "e_1 = paddle.to_tensor(np.sqrt(p) * np.array([[0, 1], [1, 0]], dtype=complex_dtype))\n",
    "Kraus_ops = [e_0, e_1]\n",
    "\n",
    "# 初始化量子电路\n",
    "num_qubits = 1\n",
    "cir = Circuit(num_qubits)\n",
    "\n",
    "# 添加自定义噪声，其输入为 Kraus 算符的列表\n",
    "cir.kraus_repr(Kraus_ops, 0)\n",
    "\n",
    "# 执行电路\n",
    "fin_state = cir(init_state)\n",
    "\n",
    "# 比较结果\n",
    "cir_1 = Circuit(num_qubits)\n",
    "cir_1.bit_flip(p, 0)\n",
    "fin_state_1 = cir_1(init_state)\n",
    "print('经过了自定义信道之后的量子态是：\\n', fin_state.data.numpy())\n",
    "print('\\n经过了比特反转信道之后的量子态是：\\n', fin_state_1.data.numpy())\n",
    "print('\\n两个态是否相同？', bool((fin_state.data - fin_state_1.data).abs().sum() < 1e-6))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "proper-director",
   "metadata": {},
   "source": [
    "按照上述例子，用户可以通过自定义 *Kraus* 算符的方式实现特定的信道。"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "tested-elder",
   "metadata": {},
   "source": [
    "## 拓展：Paddle Quantum 模拟含噪纠缠资源\n",
    "\n",
    "\n",
    "许多重要的量子技术，例如量子隐形传态、态转换、分布式量子计算等都需要纠缠资源的预先分配。以纠缠量子比特对为例，在理想情况下，我们希望分配的纠缠资源处于**最大纠缠态**（Maximally entangled state)。但是在实际的应用中，纠缠资源往往在制备、传输以及保存的过程中会和环境发生相互作用，从而引入噪声。下面，我们用 Paddle Quantum 中的去极化信道来模拟一个简单的场景，白噪声对贝尔态的影响："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "id": "spread-monkey",
   "metadata": {
    "ExecuteTime": {
     "end_time": "2021-04-08T05:24:35.552425Z",
     "start_time": "2021-04-08T05:24:35.519733Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "初态和贝尔态之间的保真度为 1\n",
      "经过了传输（去极化信道）之后的纠缠对和贝尔态的保真度为 0.81333\n",
      "又经过了存储（振幅阻尼信道）之后的纠缠对和贝尔态的保真度为 0.66752\n"
     ]
    }
   ],
   "source": [
    "import paddle\n",
    "from paddle import matmul, trace\n",
    "from paddle_quantum.ansatz import Circuit\n",
    "from paddle_quantum.state import bell_state\n",
    "\n",
    "# 噪声参数\n",
    "p_trans = 0.1\n",
    "p_store = 0.01\n",
    "\n",
    "# 创建用来模拟噪声的量子电路\n",
    "num_qubits = 2\n",
    "cir = Circuit(num_qubits)\n",
    "\n",
    "# 这里的初态是制备好的贝尔态\n",
    "init_state = bell_state(2)\n",
    "\n",
    "# 分别在两个量子比特上添加去极化信道，表示在传输过程中引入的噪声\n",
    "cir.depolarizing(p_trans, 0)\n",
    "cir.depolarizing(p_trans, 1)\n",
    "\n",
    "# 用模拟噪声的电路来演化该初态\n",
    "status_mid = cir(init_state)\n",
    "\n",
    "# 分别在两个量子比特上添加振幅阻尼信道，表示在保存过程中引入的噪声\n",
    "cir.amplitude_damping(p_store, 0)\n",
    "cir.amplitude_damping(p_store, 1)\n",
    "\n",
    "# 用模拟噪声的电路来演化该初态\n",
    "status_fin = cir(status_mid)\n",
    "fidelity_mid = paddle.real(trace(matmul(init_state.data, status_mid.data)))\n",
    "fidelity_fin = paddle.real(trace(matmul(init_state.data, status_fin.data)))\n",
    "\n",
    "print(\"初态和贝尔态之间的保真度为\", 1)\n",
    "print(\"经过了传输（去极化信道）之后的纠缠对和贝尔态的保真度为 {:.5f}\".format(fidelity_mid.numpy()[0]))\n",
    "print(\"又经过了存储（振幅阻尼信道）之后的纠缠对和贝尔态的保真度为 {:.5f}\".format(fidelity_fin.numpy()[0]))"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "id": "comparable-athletics",
   "metadata": {},
   "source": [
    "**注释：** 在 [纠缠蒸馏](../locc/EntanglementDistillation_LOCCNET_CN.ipynb) 的教程中我们介绍了如何利用 Paddle Quantum 中的 LoccNet 模块来研究纠缠蒸馏，即利用多个含噪声的纠缠对来提取高保真度的纠缠对，感兴趣的读者可以前往阅读。"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "elegant-bikini",
   "metadata": {},
   "source": [
    "## 应用： Paddle Quantum 模拟含噪变分量子本征求解器（VQE）\n",
    "\n",
    "\n",
    "变分量子本征求解器（Variational Quantum Eigensolver）[5] 可以用变分量子电路来计算某个给定哈密顿量的基态能量，关于其具体的原理和背景在之前的教程 [变分量子本征求解器](../quantum_simulation/VQE_CN.ipynb) 中有详细的讲解，感兴趣的读者可以前往阅读。\n",
    "\n",
    "在这里，我们尝试用一个简单的 VQE 电路来求解如下哈密顿量的基态能量：\n",
    "\n",
    "$$ \n",
    "H = 0.4 \\, Z \\otimes I + 0.4 \\, I \\otimes Z + 0.2 \\, X \\otimes X. \n",
    "\\tag{14}\n",
    "$$\n",
    "\n",
    "特别地，我们将在电路中引入振幅阻尼信道来模拟电路运行时的 $T_1$ 噪声，让我们分别来看一下含噪电路和非含噪电路在该任务上的表现："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "id": "unavailable-october",
   "metadata": {
    "ExecuteTime": {
     "end_time": "2021-04-08T05:34:47.301281Z",
     "start_time": "2021-04-08T05:34:47.293619Z"
    }
   },
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "import paddle\n",
    "from paddle_quantum.ansatz import Circuit\n",
    "from paddle_quantum.qinfo import pauli_str_to_matrix\n",
    "\n",
    "# 超参数设置\n",
    "num_qubits = 2\n",
    "theta_size = 4\n",
    "ITR = 100\n",
    "LR = 0.4\n",
    "SEED = 999    \n",
    "p = 0.1\n",
    "\n",
    "# 首先生成泡利字符串表示下的哈密顿量\n",
    "H_info = [[0.4, 'z0'], [0.4, 'z1'], [0.2, 'x0,x1']]\n",
    "\n",
    "# 把记录的关于哈密顿量的信息转化为矩阵表示\n",
    "complex_dtype = paddle_quantum.get_dtype()\n",
    "H_matrix = pauli_str_to_matrix(H_info, num_qubits).numpy().astype(complex_dtype)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "id": "protected-difficulty",
   "metadata": {
    "ExecuteTime": {
     "end_time": "2021-04-08T05:34:51.742273Z",
     "start_time": "2021-04-08T05:34:47.726698Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "========== Training Noisy VQE ==========\n",
      "iter: 0   loss: -0.3881\n",
      "iter: 10   loss: -0.6246\n",
      "iter: 20   loss: -0.6454\n",
      "iter: 30   loss: -0.6611\n",
      "iter: 40   loss: -0.6608\n",
      "iter: 50   loss: -0.6616\n",
      "iter: 60   loss: -0.6620\n",
      "iter: 70   loss: -0.6621\n",
      "iter: 80   loss: -0.6621\n",
      "iter: 90   loss: -0.6622\n",
      "========== Training Noise Free VQE ==========\n",
      "iter: 0   loss: 0.0636\n",
      "iter: 10   loss: -0.6282\n",
      "iter: 20   loss: -0.7518\n",
      "iter: 30   loss: -0.8124\n",
      "iter: 40   loss: -0.8229\n",
      "iter: 50   loss: -0.8208\n",
      "iter: 60   loss: -0.8243\n",
      "iter: 70   loss: -0.8242\n",
      "iter: 80   loss: -0.8246\n",
      "iter: 90   loss: -0.8246\n",
      "\n",
      "含噪电路计算得到的基态能量是:  -0.6621563 Ha\n",
      "不含噪电路计算得到的基态能量是:  -0.82461804 Ha\n",
      "真实的基态能量为:  -0.82462114 Ha\n"
     ]
    }
   ],
   "source": [
    "class vqe_noisy(paddle.nn.Layer):\n",
    "    \n",
    "    def __init__(self):\n",
    "        super(vqe_noisy, self).__init__()\n",
    "\n",
    "        # 初始量子电路\n",
    "        self.cir = Circuit(num_qubits)\n",
    "        \n",
    "        # 添加参数化量子电路\n",
    "        self.cir.ry([0, 1])\n",
    "         \n",
    "        self.cir.cnot([0, 1])\n",
    "        \n",
    "        self.cir.ry([0, 1])\n",
    "        \n",
    "        # 添加振幅阻尼 AD 噪声\n",
    "        self.cir.amplitude_damping(p, [0, 1])\n",
    "        \n",
    "    # 定义损失函数和前向传播机制\n",
    "    def forward(self):\n",
    "\n",
    "        # 运行密度矩阵模式\n",
    "        state = self.cir(init_state)\n",
    "\n",
    "        # 关于观测量 H_info 的期望值\n",
    "        loss = loss_func(state)\n",
    "        \n",
    "        return loss, self.cir\n",
    "    \n",
    "# 创建一个不含噪声的 VQE 电路\n",
    "class vqe_noise_free(paddle.nn.Layer):\n",
    "    \n",
    "    def __init__(self):\n",
    "        super(vqe_noise_free, self).__init__()\n",
    "\n",
    "        self.cir = Circuit(num_qubits)\n",
    "        self.cir.ry([0, 1])\n",
    "        self.cir.cnot([0, 1])\n",
    "        self.cir.ry([0, 1])\n",
    "\n",
    "    def forward(self):\n",
    "        \n",
    "        state = self.cir(init_state)\n",
    "        loss = loss_func(state)\n",
    "        \n",
    "        return loss, self.cir\n",
    "    \n",
    "# 训练含噪 VQE 电路\n",
    "print('========== Training Noisy VQE ==========')\n",
    "loss_list = []\n",
    "parameter_list = []\n",
    "\n",
    "# 定义参数维度\n",
    "vqe = vqe_noisy()\n",
    "\n",
    "# 一般来说，我们利用Adam优化器来获得相对好的收敛，当然你可以改成SGD或者是RMS prop.\n",
    "opt = paddle.optimizer.Adam(learning_rate = LR, parameters = vqe.parameters())\n",
    "\n",
    "# 定义初始态\n",
    "init_state = paddle_quantum.state.zero_state(num_qubits)\n",
    "\n",
    "# 定义损失函数\n",
    "loss_func = paddle_quantum.loss.ExpecVal(paddle_quantum.Hamiltonian(H_info))\n",
    "\n",
    "# 优化循环\n",
    "for itr in range(ITR):\n",
    "\n",
    "    # 前向传播计算损失函数\n",
    "    loss, cir = vqe()\n",
    "\n",
    "    # 反向传播极小化损失函数\n",
    "    loss.backward()\n",
    "    opt.minimize(loss)\n",
    "    opt.clear_grad()\n",
    "\n",
    "    # 记录学习曲线\n",
    "    loss_list.append(loss.numpy()[0])\n",
    "    parameter_list.append(vqe.parameters()[0].numpy())\n",
    "    if itr % 10 == 0:\n",
    "        print('iter:', itr, '  loss: %.4f' % loss.numpy())\n",
    "        \n",
    "# 用同样的方式训练不含噪的 VQE 电路\n",
    "print('========== Training Noise Free VQE ==========')\n",
    "loss_list_no_noise = []\n",
    "parameter_list_no_noise = []\n",
    "\n",
    "vqe_no_noise = vqe_noise_free()\n",
    "opt_no_noise = paddle.optimizer.Adam(learning_rate = LR, parameters = vqe_no_noise.parameters())    \n",
    "\n",
    "for itr in range(ITR):\n",
    "\n",
    "    loss, cir = vqe_no_noise()\n",
    "\n",
    "    loss.backward()\n",
    "    opt_no_noise.minimize(loss)\n",
    "    opt_no_noise.clear_grad()\n",
    "\n",
    "    loss_list_no_noise.append(loss.numpy()[0])\n",
    "    parameter_list_no_noise.append(vqe_no_noise.parameters()[0].numpy())\n",
    "    if itr % 10 == 0:\n",
    "        print('iter:', itr, '  loss: %.4f' % loss.numpy())\n",
    "\n",
    "\n",
    "print('\\n含噪电路计算得到的基态能量是: ', loss_list[-1], \"Ha\")\n",
    "print('不含噪电路计算得到的基态能量是: ', loss_list_no_noise[-1], \"Ha\")\n",
    "print('真实的基态能量为: ', np.linalg.eigh(H_matrix)[0][0], \"Ha\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "important-testing",
   "metadata": {},
   "source": [
    "可以看到，含噪的变分量子本征求解器的效果要差于不含噪的版本，无法达到化学精度的要求 $\\varepsilon = 0.0016$ Ha。"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "extensive-forge",
   "metadata": {},
   "source": [
    "## 总结\n",
    "\n",
    "噪声是 NISQ 时代量子设备的一个不可忽视的特征。在近期的量子技术中，我们有必要将噪声考虑进计算模型中。因此，设计对于噪声鲁棒的量子算法，乃至于设计噪声抑制方案，都是 NISQ 时代的一大重要方向。基于 Paddle Quantum 新增的噪声模块，我们希望为开发者提供贴近真实系统的近期量子计算应用的开发平台，帮助使用者一起思考如何更好地使用含噪量子设备以及如何设计出更鲁棒的量子算法，进而更好地通过近期量子设备实现人工智能、量子化学等领域的应用。\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "inappropriate-board",
   "metadata": {},
   "source": [
    "---\n",
    "\n",
    "## 参考文献\n",
    "\n",
    "[1] Iverson, J. K., & Preskill, J. Coherence in logical quantum channels. [New Journal of Physics, 22(7), 073066 (2020).](https://iopscience.iop.org/article/10.1088/1367-2630/ab8e5c)\n",
    "\n",
    "[2] Nielsen, M. A. & Chuang, I. L. Quantum computation and quantum information. Cambridge university press (2010).\n",
    "\n",
    "[3] Preskill, J. Quantum Information Lecture Notes. Chapter 3 (2018).\n",
    "\n",
    "[4] Chirolli, L., & Burkard, G. Decoherence in solid-state qubits. [Advances in Physics, 57(3), 225-285 (2008).](https://www.tandfonline.com/doi/abs/10.1080/00018730802218067)\n",
    "\n",
    "[5] Peruzzo, A. et al. A variational eigenvalue solver on a photonic quantum processor. [Nat. Commun. 5, 4213 (2014).](https://www.nature.com/articles/ncomms5213)"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.8.13"
  },
  "toc": {
   "base_numbering": 1,
   "nav_menu": {},
   "number_sections": true,
   "sideBar": true,
   "skip_h1_title": false,
   "title_cell": "Table of Contents",
   "title_sidebar": "Contents",
   "toc_cell": false,
   "toc_position": {},
   "toc_section_display": true,
   "toc_window_display": false
  },
  "varInspector": {
   "cols": {
    "lenName": 16,
    "lenType": 16,
    "lenVar": 40
   },
   "kernels_config": {
    "python": {
     "delete_cmd_postfix": "",
     "delete_cmd_prefix": "del ",
     "library": "var_list.py",
     "varRefreshCmd": "print(var_dic_list())"
    },
    "r": {
     "delete_cmd_postfix": ") ",
     "delete_cmd_prefix": "rm(",
     "library": "var_list.r",
     "varRefreshCmd": "cat(var_dic_list()) "
    }
   },
   "types_to_exclude": [
    "module",
    "function",
    "builtin_function_or_method",
    "instance",
    "_Feature"
   ],
   "window_display": false
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
